/**
 * 函数描述：js调用webview事件
 *
 * jsBridge.callHandler(method, data, callBack(response));
 * @param method {string} 方法名
 * @param data {Object} 参数
 * @return {Object} 回调
 */

/**
 * 函数描述：webView调用JS事件
 *
 * jsBridge.registerHandler(method, callBack(response));
 * @param method {string} 方法名
 * @return {Object} 回调
 */

let JsBridge = {
  init: function(callback) {
    const u = navigator.userAgent
    const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    if (!isiOS) {
      if (window.WebViewJavascriptBridgeAndroid) {
        callback(window.WebViewJavascriptBridgeAndroid)
      } else {
        document.addEventListener(
          'WebViewJavascriptBridgeReady',
          function() {
            callback(window.WebViewJavascriptBridgeAndroid)
          },
          false
        )
      }
      // 安卓的使用本地注入js方法为了避免冲突IOS服务器注入方法，将安卓封装进window的方法名改成安卓专属
    } else {
      // ios端交互仅需要提供约定好的拦截地址就可以了
      if (window.WebViewJavascriptBridge) {
        return callback(window.WebViewJavascriptBridge)
      }
      if (window.WVJBCallbacks) {
        return window.WVJBCallbacks.push(callback)
      }
      window.WVJBCallbacks = [callback]
      let WVJBIframe = document.createElement('iframe')
      WVJBIframe.style.display = 'none'
      WVJBIframe.src = 'https://__bridge_loaded__'
      document.documentElement.appendChild(WVJBIframe)
      setTimeout(function() {
        document.documentElement.removeChild(WVJBIframe)
      }, 0)
    }
  },
  first: function() {
    const u = navigator.userAgent
    const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
    if (!isiOS) {
      let _this = this
      _this.init(function(bridge) {
        bridge.init(function(message, responseCallback) {
          responseCallback(message)
        })
      })
    }
  },
  registerHandler: function(name, fun) {
    let _this = this
    _this.init(function(bridge) {
      bridge.registerHandler(name, fun)
    })
  },
  callHandler: function(name, data, fun) {
    let _this = this
    _this.init(function(bridge) {
      bridge.callHandler(name, data, fun)
    })
  }
}

JsBridge.first()

export {
  JsBridge
}